package com.ihome.framework.core.validator;

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.parameternameprovider.ParanamerParameterNameProvider;
import org.springframework.stereotype.Component;

import com.ihome.framework.core.exception.BusinessException;

/**
 * 用于校验普通对象的校验工具
 * 
 * @author zhengxiaohong
 *
 */
@Component
public class ValidatorUtil {

	private volatile ValidatorFactory validatorFactory;
	private volatile Validator validator;

	public ValidatorUtil() {
		if (validatorFactory == null) {
			validatorFactory = Validation.byProvider(HibernateValidator.class).configure().failFast(true)
					.parameterNameProvider(new ParanamerParameterNameProvider()).buildValidatorFactory();
		}
		validator = validatorFactory.getValidator();
	}

	public Set<ConstraintViolation<Object>> validate(Object obj) {
		return validator.validate(obj);
	}

	public void validateWithException(Object obj) {
		Set<ConstraintViolation<Object>> violations = validator.validate(obj);
		if (!violations.isEmpty()) {
			throw new BusinessException(getViolationMsg(violations));
		}
	}

	public void validateWithException(Object obj, Class<?>... groups) {
		Set<ConstraintViolation<Object>> violations = validator.validate(obj, groups);
		if (!violations.isEmpty()) {
			throw new BusinessException(getViolationMsg(violations));
		}
	}

	protected String getViolationMsg(Set<ConstraintViolation<Object>> violations) {
		StringBuilder sb = new StringBuilder();
		Iterator<ConstraintViolation<Object>> iter = violations.iterator();
		while (iter.hasNext()) {
			ConstraintViolation<Object> cv = iter.next();
			String argsName = cv.getPropertyPath().toString();
			sb.append(argsName);
			sb.append(cv.getMessage());
			if (iter.hasNext()) {
				sb.append(",");
			}
		}
		return sb.toString();
	}
}
